﻿

//HTML中需要添加的自定义属性说明
//empty:bool值,是否允许为空
//emptyErrorMsg:不允许为空时，空值的错误信息
//validata:验证的内容,empty为空,其他需要验证数据格式的validata值请参照该文件下方regName的值
//errorMsg:数据格式有误时显示的错误信息
//url:发送ajax请求时的url地址
//trueMsg:ajax返回的data值为bool值。返回true时显示的信息
//falseMsg:返回false时显示的信息,若是其他字符类型则显示在errorMsg中。

$(function () {
    //对数据格式的验证
    //参数说明：
    //empty:是否允许为空。缺省为不可为空。bool:true/false
    //errorMsg:错误信息
    //emptyErrorMsg:为空的错误信息，缺省为红*
    //limitLength:最大长度，字节计数
    //validata:验证类型：email,tel,phone,postcode,number,datetime,money.....
    $("input[validata!=''][validata!='idcard'][validata!='ajax'][validata!='password2']").blur(function () {
        var validataName = $(this).attr("validata");  //验证内容 
        var isAllowEmpty = $(this).attr("empty");  //是否允许为空
        var errorMsg = $(this).attr("errorMsg"); //错误提示信息
        var emptyErrorMsg = $(this).attr("emptyErrorMsg"); //为空时的错误信息
        var limitLength = $(this).attr("limitLength"); //字段最大长度
        var limitLength_errorMsg="字段最大长度不能超过"+limitLength+"位";
        var regString = returnRegString(validataName);
        if (validataName != "" || validataName != null || validataName != undefined) {
            if ($(this).next().attr("type") != "vmsg") {
                $(this).after("<span type='vmsg' style='color:#ff0000'></span>");
            }
            var errorSpan = $(this).next();
            var m;
            var n;
            if(validataName=='decimal'){
                m=$(this).attr("m");
            	n=$(this).attr("n");
            	errorMsg='数字格式错误,'+(m-n)+'位整数'+n+'位小数';
            }
            //如果允许为空属性值为空或不写则默认为不允许为空，empty为bool值:true/false
            if (isAllowEmpty == "" || isAllowEmpty == null || isAllowEmpty == undefined || isAllowEmpty.toLowerCase() == "false") {
                //判空的同时对输入的数据进行验证
                if ($(this).val() == "") {
                   errorSpan.text("").text(returnErrorMsg(emptyErrorMsg,$(this)));
                } else {
                	if(validataName=='decimal'&&$(this).val().match(check(m,n)) == null){
                		errorSpan.text("").text(returnErrorMsg(errorMsg,$(this)));
                	}else{
                	if(!checkLength($(this).val(),limitLength)){
                		errorSpan.text("").text(returnErrorMsg(limitLength_errorMsg,$(this)));
                	}else{
                		if (validataName!='len'&&$(this).val().match(regString) == null) {
                       		errorSpan.text("").text(returnErrorMsg(errorMsg,$(this)));
	                    } else {
	                        errorSpan.text("");
	                    }
                	}
                	}
                	
                    
                }
            } else if (isAllowEmpty.toLowerCase() == "true") {
                //允许为空，则只对输入数据一做验格式的验证
                if ($(this).val() != "") {
                if(validataName=='decimal'&&$(this).val().match(check(m,n)) == null){
                		errorSpan.text("").text(returnErrorMsg(errorMsg,$(this)));
                	}else{
                	if(!checkLength($(this).val(),limitLength)){
                		errorSpan.text("").text(returnErrorMsg(limitLength_errorMsg,$(this)));
                	}else{
	                    if (validataName!='len'&&$(this).val().match(regString) == null) {
	                        errorSpan.text("").text(returnErrorMsg(errorMsg,$(this)));
	                    } else {
	                       errorSpan.text("");
	                    }
	                }
                }
                }
            }
        }
    });

    //身份证验证，身份证分15与18位
    //参数说明：
    //empty:是否允许为空。缺省为不可为空。bool:true/false
    //errorMsg:错误信息
    //emptyErrorMsg:为空的错误信息，缺省为红*
    //validata:验证类型：email,tel,phone,postcode,number,datetime,money.....
    /*不用
    $("input[validata='idcard']").blur(function () {
        var validataName = $(this).attr("validata");  //验证内容 
        var isAllowEmpty = $(this).attr("empty");  //是否允许为空
        var errorMsg = $(this).attr("errorMsg"); //错误提示信息
        var emptyErrorMsg = $(this).attr("emptyErrorMsg"); //为空时的错误信息
        var regString = "";
        if ($(this).next().attr("type") != "vmsg") {
            $(this).after("<span type='vmsg' style='color:#ff0000'></span>");
        }
        var errorSpan = $(this).next();
        //如果允许为空属性值为空或不写则默认为不允许为空，empty为bool值:true/false
        if (isAllowEmpty == "" || isAllowEmpty == null || isAllowEmpty == undefined || isAllowEmpty.toLowerCase() == "false") {
            //判空的同时对输入的数据进行验证
            if ($(this).val() == "") {
                errorSpan.text("").text(returnErrorMsg(emptyErrorMsg));
            } else {
                if ($(this).val().length == 15 || $(this).val().length == 18) {
                    if ($(this).val().length == 15) {
                        regString = "^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$";
                    } else {
                        regString = "^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$";
                    }
                    if ($(this).val().match(regString) == null) {
                        errorSpan.text("").text(returnErrorMsg(errorMsg));
                    } else {
                        errorSpan.text("");
                    }
                } else {
                    errorSpan.text("").text(returnErrorMsg(errorMsg));
                }
            }
        } else if (isAllowEmpty.toLowerCase() == "true") {
            //允许为空，则只对输入数据一做验格式的验证
            if ($(this).val() != "") {
                if ($(this).val().length == 15 || $(this).val().length == 18) {
                    if ($(this).val().length == 15) {
                        regString = "^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$";
                    } else {
                        regString = "^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9Xx])$";
                    }
                    if ($(this).val().match(regString) == null) {
                        errorSpan.text("").text(returnErrorMsg(errorMsg));
                    } else {
                        errorSpan.text("");
                    }
                } else {
                    errorSpan.text("").text(returnErrorMsg(errorMsg));
                }
            }
        }
    });*/


    //参数说明：
    //empty:是否允许为空true/false
    //errorMsg:验证数据格式的错误信息
    //emptyErrorMsg:验证非空的错误信息
    //url:ajax提交请求的地址
    //trueMsg:返回的结果为true时的信息
    //falseMsg:返回的结果为false时的信息
    //ajax验证，返回bool值或返回字符串
    /*基本没用
    $("input[validata='ajax']").blur(function () {
        var isAllowEmpty = $(this).attr("empty");
        var errorMsg = $(this).attr("errorMsg");
        var emptyErrorMsg = $(this).attr("emptyErrorMsg");
        var url = $(this).attr("url");
        var trueMsg = $(this).attr("trueMsg");
        var falseMsg = $(this).attr("falseMsg");
        if ($(this).next().attr("type") != "vmsg") {
            $(this).after("<span type='vmsg' style='color:#ff0000'></span>");
        }
        var errorSpan = $(this).next();
        //如果允许为空属性值为空或不写则默认为不允许为空，empty为bool值:true/false
        if (isAllowEmpty == "" || isAllowEmpty == null || isAllowEmpty == undefined || isAllowEmpty.toLowerCase() == "false") {
            //判空的同时对输入的数据进行验证
            if ($(this).val() == "") {
                errorSpan.text("").text(returnErrorMsg(emptyErrorMsg));
            } else {
                $.get(url + "?" + $(this).attr("name") + "=" + $(this).val(), function (data) {
                    if (data.toLowerCase() == "true") {
                        errorSpan.text("").text(returnErrorMsg(returnErrorMsg(trueMsg)));
                    } else if (data.toLowerCase() == "false") {
                        errorSpan.text("").text(returnErrorMsg(returnErrorMsg(falseMsg)));
                    } else {
                        errorSpan.text("").text(returnErrorMsg(returnErrorMsg(errorMsg)));
                    }
                });
            }
        } else if (isAllowEmpty.toLowerCase() == "true") {
            if ($(this).val() != "") {
                $.get(url + "?" + $(this).attr("name") + "=" + $(this).val(), function (data) {
                    if (data.toLowerCase() == "true") {
                        errorSpan.text("").text(returnErrorMsg(returnErrorMsg(trueMsg)));
                    } else if (data.toLowerCase() == "false") {
                        errorSpan.text("").text(returnErrorMsg(returnErrorMsg(falseMsg)));
                    } else {
                        errorSpan.text("").text(returnErrorMsg(returnErrorMsg(errorMsg)));
                    }
                });
            }
        }
    });*/

    //密码验证
    $("input[validata='password2']").blur(function () {
        var errorMsg = $(this).attr("errorMsg");
        var diffErrorMsg = $(this).attr("diffMsg");
        if ($(this).next().attr("type") != "vmsg") {
            $(this).after("<span type='vmsg' style='color:#ff0000'></span>");
        }
        var errorSpan = $(this).next();
        if ($(this).val() == "") {
            errorSpan.text("").text(returnErrorMsg(returnErrorMsg(errorMsg)));
        } else {
            if ($(this).val() != $("input[type='password'][validata='empty']").val()) {
                errorSpan.text("").text(returnErrorMsg(returnErrorMsg(diffErrorMsg)));
            } else {
                errorSpan.text("");
            }
        }
    });

    //提交数据时对数据进行验证
    /*弃用
    $("input[type='submit']").click(function () {
        var validataCollections = $("input[validata!='']");
        var validataCount = 0;
        for (var i = 0; i < validataCollections.length; i++) {
            if (($("input[validata!='']:eq(" + i + ")").next().attr("type") == "vmsg") && ($("input[validata!='']:eq(" + i + ")").next().text() != "")) {
                //$.prompt({ content: $("input[validata!='']:eq(" + i + ")").next().text(), refresh: false });
                //alert($("input[validata!='']:eq(" + i + ")").next().text());
                return false;
            } else if (($("input[validata!='']:eq(" + i + ")").next().attr("type") == undefined) && ($("input[validata!='']:eq(" + i + ")").next().text() == "")) {
                //$.prompt({ content: "请输入完整，合法的数据！", refresh: false });
                alert("请输入完整，合法的数据！");
                return false;
            } else {
                validataCount = validataCount + 1;
            }
        }
        if (validataCount == validataCollections.length) {
            $(this).submit();
        } else {
            return false;
        }
    });*/
});

function checkSubmit() {
        var validataCollections = $("input[validata!='']");
        var validataCount = 0;
        for (var i = 0; i < validataCollections.length; i++) {
            if (($("input[validata!='']:eq(" + i + ")").next().attr("type") == "vmsg") && ($("input[validata!='']:eq(" + i + ")").next().text() != "")) {
                //$.prompt({ content: $("input[validata!='']:eq(" + i + ")").next().text(), refresh: false });
                alert($("input[validata!='']:eq(" + i + ")").next().text());
                $("input[validata!='']:eq(" + i + ")").focus();
                return false;
            } else if (($("input[validata!='']:eq(" + i + ")").next().attr("type") == undefined) && ($("input[validata!='']:eq(" + i + ")").next().text() == "")) {
                //$.prompt({ content: "请输入完整，合法的数据！", refresh: false });
                alert("请确认是否输入该项！");
                $("input[validata!='']:eq(" + i + ")").focus();
                return false;
            } else {
                validataCount = validataCount + 1;
            }
        }
        if (validataCount == validataCollections.length) {
           return true;
        } else {
            return false;
        }
    }

//根据不同的验证内容，返回相应的正则表达式
function returnRegString(regName) {
    if (regName == "email") {
        return "^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$";  //邮箱
    } else if (regName == "tel") {
        return "^(86)?(-)?(0[0-9]{2,3})?(-)?([0-9]{7,8})(-)?([0-9]{3,5})?$";  //电话
    } else if (regName == "phone") {
        return "(^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^0?[1][3587][0-9]{9}$)";  //手机
    } else if (regName == "postcode") {
        return "^([0-9]{6})$";    //邮编
    } else if (regName == "number") {
        return "^(0|([1-9]+[0-9]*))(.[0-9]+)?$";   //数字
    } else if (regName == "decimal") {
        return "^[0-9]+([.][0-9]+)?$";    //浮点
    } else if (regName == "money") {
        return "^([0-9])$";    //货币
    } else if (regName == "website") {  //网址
        return "(http://|https://){0,1}[\w\/\.\?\&\=]+";
    } else if (regName == "fax") {  //传真
        return "^[+]{0,1}([0-9]){1,3}[ ]?([-]?(([0-9])|[ ]){1,12})+$";
    } else if (regName == "int") {   //整数
        return "^(-){0,1}\d+$";
    } else if (regName == "pInt") {   //正整数
        return "^\\d+$";
    } else if (regName == "nInt") {  //负整数
        return "^-\d+$";
    } else if (regName == "nandl") {   //数字与字母
        return "[a-zA-Z0-9]";
    } else if (regName == "chinese") {   //是否含有中文字符
        return "[\u4e00-\u9fa5]";
    }
}
//正对数据库类型decimal(m,n),m位数，n位小数
function check(m,n){
	var reg="";
	if(m>0&&n>0){
	if(m-n>1)
	    reg="^(0|[1-9]\\d{0,"+(m-n-1)+"})(\\.\\d{1,"+n+"})?$";
	if(m-n==1)
		reg="^(\\d)(\\.\\d{1,"+n+"})?$";
		//reg="(^[0-9]{1,"+m+"}$)|(^[0-9]{1,"+m+"}[\.]{1}[0-9]{1,"+n+"}$)";
	}else if(m>0&&n==0){
		//reg="(^[0-9]{1,"+m+"}$)";
		if(m-n>1)
		reg="^(0|[1-9]\\d{0,"+(m-n-1)+"})$";
		if(m-n==1)
		reg="^[0-9]$";
		
	}
      //reg="(^[0-9]{1,"+m+"}$)|(^[0-9]{1,"+m+"}[\.]{1}[0-9]{1,"+n+"}$)";
        return reg;
} 


//返回错误信息
function returnErrorMsg(errorMsg,e) {
	//e.focus();
    if (errorMsg == undefined) {
        return "请输入正确的数据！";
    } else {
        return errorMsg;
    }
}
function checkLength(value,len){
	var valLength=0;
	for(var ii=0;ii<value.length;ii++){
		var word=value.substring(ii,1);
		if(/[^\x00-\xff]/g.test(word)){
			valLength+=2;
		}else{
			valLength++;
		}
	}
	if(valLength>len){
		return false;
	}
	return true;
}